/* @(#)SQLUpdate.java 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mwt.xml.xdbforms.dblayer.query.impl;

import java.util.ArrayList;
import java.util.List;
import mwt.xml.xdbforms.dblayer.query.Criteria;
import mwt.xml.xdbforms.dblayer.query.SQLOperation;

/**
 * Definisce una classe per la definizione di una query di aggiornamento
 * Per vedere una descrizione dei metodi fare riferiemento all'interfaccia
 * SQLOperation.
 * @see SQLOperation
 * @author Gianfranco Murador, Matteo Ferri, Cristian Castiglia
 * 
 */
public class SQLUpdate extends SQLOperation {

    private StringBuilder statement;
    private List<SQLParameter> parameters = null;
    private List<Object> values = null;
    private Criteria criteria;
    private boolean isCompiled = false;

    public SQLUpdate(String table) {
        statement = new StringBuilder("UPDATE " + table + " SET ");
        parameters = new ArrayList<SQLParameter>();
        values = new ArrayList<Object>();
    }

  
    @Override
    public void declareParameter(SQLParameter sqlp, Object value) {
        parameters.add(sqlp);
        values.add(value);
    }

    @Override
    public void compile() throws RuntimeException {



       // int paramLength = parameters.size();
       // int valuesLength = values.size();

       /* if (paramLength != valuesLength) {
            throw new RuntimeException("Error, parameters and values mismatch");
        }*/

        for (int i = 0; i < parameters.size(); i++) {
            SQLParameter sQLParameter = parameters.get(i);
            statement.append(sQLParameter.getName() + "=?,");

        }
        statement.deleteCharAt(statement.length() - 1);
        statement.append(" WHERE ");


        if (criteria != null) {
            statement.append(criteria.toSqlString());
        } else {
            throw new RuntimeException("Error, Critera is required for update");
        }


        isCompiled = true;

    }

    @Override
    public String toString() {
        if (isCompiled) {
            return statement.toString();
        } else {
            compile();
            return statement.toString();
        }
    }

    @Override
    public List<SQLParameter> getParameters() {
        return parameters;
    }

    @Override
    public Object[] getValues() {
        return values.toArray();
    }

    @Override
    public void addCriteria(Criteria c) {
        /*criteria = c;
        values.add(c.getValues());*/
         if (criteria == null) {
            criteria = c;
            //  values.add(c.getValues());
            Object[] v = c.getValues();

            for (int i = 0; i < v.length; i++) {
                Object object = v[i];

                System.out.println("SQLUpdate: "+object.toString());
                values.add(object);

            }

        }
    }
}
